//
//  SendEmailView.m
//  Bespoke
//
//  Created by Cheng on 12/11/8.
//
//

#import "SendEmailView.h"
#import "RequestAPIFunction.h"
#import "GDataXMLNode.h"
#import "Split.h"

#define KEYBOARDHEIGHT 360

#define SendEmailInMyBook_API @"http://54.235.166.43/BeSpokeAPI/Email/SendEmailInMyBook.php"

@implementation SendEmailView
@synthesize TVw_Email, AB_CurrentBook, BK_En_object;
@synthesize delegate;


- (void)InitTextView {
    
    TVw_Email.textColor = [UIColor lightGrayColor];
    TVw_Email.text = @"Enter e-mail";
    TVw_Email.delegate = self;
}

-(IBAction)ClosePressed:(id)sender {
    [self.delegate DidCloseView];
}

-(IBAction)SendEmailPressed:(id)sender {
    
    NSMutableString *NS_Email = [[NSMutableString alloc] init];
    NSString *NS_FirstName;
    
    //Get User NickName.
    if ([BK_En_object.fullName rangeOfString:@" "].location!=NSNotFound) {
        
        NSRange RangeIndex = [BK_En_object.fullName rangeOfString:@" "];
        NS_FirstName = [BK_En_object.fullName substringWithRange:NSMakeRange(0,RangeIndex.location)];
    }
    else
        NS_FirstName = self.BK_En_object.fullName;
    
    
    NSArray *Array_Email = [TVw_Email.text componentsSeparatedByString:@"\n"];
    
    [NS_Email appendString:[NSString stringWithFormat:@"<UserInfo FirstName=\"%@\">",NS_FirstName]];
    
    for (NSString *Email in Array_Email) {
        
        if ([Email rangeOfString:@"@"].location == NSNotFound) {
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The Email you entered is incorrect." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView show];
            return;
        }
        
        [NS_Email appendString:[NSString stringWithFormat:@"<SendEmail Name=\"%@\" />",Email]];
    }
    
    int i=0;
    
    for (MediaListsMedia *MLM_Media in AB_CurrentBook.MediaArray) {
        
        //Check Link is null.
        if (![MLM_Media.WebLink isEqualToString:@""]) {
            for (int j=i+1;j<AB_CurrentBook.MediaArray.count;j++) {
                
                //Check Link is same for other.
                if ([MLM_Media.WebLink isEqualToString:
                     ((MediaListsMedia *)[AB_CurrentBook.MediaArray objectAtIndex:j]).WebLink]) {
                    break;
                }
                else if (j+1==AB_CurrentBook.MediaArray.count) {
                    
                    [NS_Email appendString:[NSString stringWithFormat:@"<MediaInfo Weblink=\"%@\" />",[MLM_Media.WebLink SymbolParseString]]];
                }
            }
            NSLog(@"%@",MLM_Media.WebLink);
        }
        i++;
    }
    
    [NS_Email appendString:@"</UserInfo>"];
    
    [TVw_Email resignFirstResponder];
    self.center = CGPointMake(self.superview.bounds.size.width/2, self.superview.bounds.size.height/2);
    
    if ([NS_Email rangeOfString:@"<SendEmail Name="].location != NSNotFound) {
        
        NSData *responseData =
        [RequestAPIFunction XML_PostRequest:NS_Email urlString:SendEmailInMyBook_API];
        
        //No Network Connection or time out.
        if (responseData == nil)
            return;
        
        NSError *error;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
        
        //Check to upload is success.
        if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
            
            [self.delegate SendEmailSuccessed:[NSMutableArray arrayWithArray:Array_Email]];
        }
        else {
            
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert"
                                                               message:[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]
                                                              delegate:nil
                                                     cancelButtonTitle:@"Ok"
                                                     otherButtonTitles:nil];
            [AlertView show];
        }
    }
}

#pragma mark - UITextViewDelegate

- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    self.frame = CGRectMake(self.frame.origin.x, self.superview.bounds.size.height-KEYBOARDHEIGHT-self.frame.size.height, self.frame.size.width, self.frame.size.height);
    
    if ([textView.text isEqualToString:@"Enter e-mail"])
        textView.text = @"";
    textView.textColor = [UIColor blackColor];
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView {
    
    self.center = CGPointMake(self.superview.bounds.size.width/2, self.superview.bounds.size.height/2);
    
    if(textView.text.length == 0){
        textView.textColor = [UIColor lightGrayColor];
        textView.text = @"Enter e-mail";
        [textView resignFirstResponder];
    }
}

@end
